﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Diagnostics.Contracts;
using System.Web.Http.Dependencies;
using Ninject;
using Ninject.Syntax;
using Ninject.Activation;
using Ninject.Parameters;

namespace TimberSmart.Web
{
    public class NinjectDependencyScope : IDependencyScope
    {
        private IResolutionRoot resolver;

        internal NinjectDependencyScope(IResolutionRoot resolver)
        {
            Contract.Assert(resolver != null);

            this.resolver = resolver;
        }

        public void Dispose()
        {
            //var disposable = resolver as IDisposable;
            //if (disposable != null)
            //    disposable.Dispose();

            //resolver = null;

            IDisposable disposable = (IDisposable)resolver;
            if (disposable != null) disposable.Dispose();
            resolver = null;
        }

        public object GetService(Type serviceType)
        {
            IRequest request = resolver.CreateRequest(serviceType, null, new Parameter[0], true, true);
            return resolver.Resolve(request).SingleOrDefault();

            //if (resolver == null)
            //    throw new ObjectDisposedException("this", "This scope has already been disposed");

            //return resolver.TryGet(serviceType);
        }

        public IEnumerable<object> GetServices(Type serviceType)
        {
            IRequest request = resolver.CreateRequest(serviceType, null, new Parameter[0], true, true);
            return resolver.Resolve(request).ToList();
            //if (resolver == null)
            //    throw new ObjectDisposedException("this", "This scope has already been disposed");

            //return resolver.GetAll(serviceType);
        }
    }
}